package logic

import (
	"context"
	"fmt"
	"shuqi-novel/models/mysql"
	"shuqi-novel/pkg"

	"shuqi-novel/shuqirpc/internal/svc"
	"shuqi-novel/shuqirpc/shuqirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *shuqirpc.RegisterRequest) (*shuqirpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var userFind mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&userFind)
	if userFind.ID != 0 {
		return nil, fmt.Errorf("账户已被注册,请前往登录")
	}

	user := mysql.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
		Name:     in.Name,
	}
	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	return &shuqirpc.RegisterResponse{UserId: int64(user.ID)}, nil
}
